<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="dictRegionFormRef"
      :model="form"
      label-width="120px"
      :rules="rules"
    >
      <el-row>
        <!-- 地区编码 -->
        <el-col :span="24">
          <el-form-item :label="$t('dictRegion.regionCode')" prop="regionCode">
            <el-input
              v-model="form.regionCode"
              :placeholder="$t('dictRegion.regionCodePlaceholder')"
              maxlength="15"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
        <!-- 地区名称 -->
        <el-col :span="24">
          <el-form-item :label="$t('dictRegion.regionName')" prop="regionName">
            <el-input
              v-model="form.regionName"
              :placeholder="$t('dictRegion.regionNamePlaceholder')"
              maxlength="60"
              show-word-limit
              @blur="handleBlur"
              clearable
            />
          </el-form-item>
        </el-col>
        <!-- 地区拼音 -->
        <el-col :span="24">
          <el-form-item
            :label="$t('dictRegion.regionPinyin')"
            prop="regionPinyin"
          >
            <el-input
              v-model="form.regionPinyin"
              :placeholder="$t('dictRegion.regionPinyinPlaceholder')"
              maxlength="60"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
        <!-- 地区类型 -->
        <el-col :span="24">
          <el-form-item :label="$t('dictRegion.regionType')" prop="regionType">
            <el-radio-group v-model="form.regionType">
              <el-radio
                v-for="item in Dict.regionTypeEnum.values"
                :key="item.key"
                :value="item.key"
                :label="item.value"
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 地区分类 -->
        <el-col :span="24">
          <el-form-item
            :label="$t('dictRegion.regionCategory')"
            prop="regionCategory"
          >
            <el-radio-group v-model="form.regionCategory">
              <el-radio
                v-for="item in Dict.regionCategoryEnum.values"
                :key="item.key"
                :value="item.key"
                :label="item.value"
              />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 上级节点 -->
        <el-col :span="24">
          <el-form-item :label="$t('dictRegion.parentId')" prop="parentId">
            <el-tree-select
              node-key="regionId"
              lazy
              v-model="form.parentId"
              :placeholder="$t('dictRegion.parentIdPlaceholder')"
              :load="handleLoad"
              :default-expanded-keys="expandedKeys"
              check-strictly
              clearable
              :props="{
                value: 'regionId',
                label: 'regionName',
                isLeaf: 'hasChildren',
                children: 'children',
              }"
            />
          </el-form-item>
        </el-col>
        <!-- 描述 -->
        <el-col :span="24">
          <el-form-item
            :label="$t('dictRegion.description')"
            prop="description"
          >
            <el-input
              v-model="form.description"
              :placeholder="$t('dictRegion.descriptionPlaceholder')"
              maxlength="120"
              show-word-limit
              clearable
              :autosize="{ minRows: 3, maxRows: 5 }"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, type PropType } from "vue";
import { type FormInstance, type FormRules, ElMessage } from "element-plus";

import { Dict } from "@/api/region";

import { dictRegionApi } from "@/api/region/os-dict-region/index";
import type {
  DictRegionKey,
  DictRegionFormReq,
  DictRegionCreateReq,
  DictRegionUpdateReq,
  DictRegionModel,
} from "@/api/region/os-dict-region/types";
import type Node from "element-plus/es/components/tree/src/model/node";

import { pinyin } from "pinyin-pro";

import { useI18n } from "vue-i18n";
import { Constant } from "@/constant";
import { extractIdsOrCodes } from "@/utils";
const { t } = useI18n();

const dictRegionFormRef = ref<FormInstance>();
const model = defineModel<boolean>();
const emits = defineEmits(["refresh", "reload"]);

let form: DictRegionFormReq = reactive<DictRegionFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask:
    "parentId,regionCode,regionName,regionPinyin,regionType,regionCategory,description",
  enable: true,
});

const rules = reactive<FormRules<DictRegionFormReq>>({
  regionCode: [
    {
      required: true,
      message: t("dictRegion.regionCodePlaceholder"),
      trigger: "change",
    },
  ],
  regionName: [
    {
      required: true,
      message: t("dictRegion.regionNamePlaceholder"),
      trigger: "change",
    },
  ],
  regionPinyin: [
    {
      required: true,
      message: t("dictRegion.regionPinyinPlaceholder"),
      trigger: "change",
    },
  ],
  regionType: [
    {
      required: true,
      message: t("dictRegion.regionTypePlaceholder"),
      trigger: "change",
    },
  ],
  regionCategory: [
    {
      required: true,
      message: t("dictRegion.regionCategoryPlaceholder"),
      trigger: "change",
    },
  ],
});

const props = defineProps({
  entityKey: {
    type: Object as PropType<DictRegionKey>,
    default: () => {},
  },
  parentId: {
    type: String as PropType<string>,
    default: "",
  },
});

form.parentId = props.parentId;
form.parentId &&
  dictRegionApi.findById({ regionId: form.parentId }).then(({ data }) => {
    getExpandedKeys(data.regionCode);
  });

// 默认展开节点数据
const expandedKeys = ref<string[]>([]);
// 获取默认展开节点
const getExpandedKeys = (regionCode: string) => {
  dictRegionApi.findByCode({ regionCode }).then(({ data }) => {
    const region = extractIdsOrCodes(data);
    expandedKeys.value = region.regionIds;
  });
};

const keys = Object.keys(props.entityKey);
const update = ref(keys.length >= 1);
// 旧数据
const oldForm: DictRegionFormReq = reactive({});
if (update.value) {
  dictRegionApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
    Object.assign(oldForm, data);
    if (form.parentId === Constant.DEFAULT_ID) {
      form.parentId = "";
    }
    getExpandedKeys(form.regionCode as string);
  });
}
// 提交表单校验
const submitForm = () => {
  dictRegionFormRef.value?.validate((valid) => {
    if (!valid) return;

    // 修改
    if (update.value) {
      dictRegionApi.update(form as DictRegionUpdateReq).then((response) => {
        if (response.status === 200) {
          ElMessage({
            message: t("common.submitSuccess"),
            type: "success",
          });
          if (model.value) {
            model.value = false;
          }
          emits("refresh", response.status === 200);
          emits("reload", oldForm, response.data);
        }
      });
      return;
    }

    // 新增
    dictRegionApi.create(form as DictRegionCreateReq).then((response) => {
      if (response.status === 200) {
        ElMessage({
          message: t("common.submitSuccess"),
          type: "success",
        });
        if (model.value) {
          model.value = false;
        }
        emits("refresh", response.status === 200);
        emits("reload", response.data);
      }
    });
  });
};

// 中文转拼音
const handleBlur = () => {
  if (!form.regionName) {
    form.regionPinyin = "";
    return;
  }
  form.regionPinyin = pinyin(form.regionName, {
    pattern: "initial",
    separator: "",
  }).toUpperCase();
};

// 关闭弹框
const closedDialog = () => {
  if (model.value) {
    model.value = false;
  }
};

// 树形选择懒加载
const handleLoad = (node: Node, resolve: (data: DictRegionModel[]) => void) => {
  // 调用接口数据
  dictRegionApi
    .findList({
      parentId: node.data.regionId,
      excludeId: props.entityKey.regionId,
    })
    .then(({ data }) => {
      resolve(
        data.results.map((item) => {
          item.hasChildren = !item.hasChildren;
          return item;
        }),
      );
    });
};
</script>
